<script setup lang='ts'>
// 自定义 规则
interface StaffHas {
    year: string,
    month: string,
    staff?: string
}

import { getCurrentInstance, ref, computed, reactive } from 'vue';
import { currentLocation } from '@/public/index'
import { onLoad, onReady } from '@dcloudio/uni-app';
import { https } from '@/api/api';
import { useUserStore, useTeamStore, useMapStore } from '@/store'
import { showToast, timeFormat,authStaff } from '@/public'
import SelecTeam from '../index/component/selectTeam.vue'
/***
 * @property 足迹
 */
const mapStore = useMapStore();
const userStore = useUserStore();
const teamStore = useTeamStore();
const _that = getCurrentInstance()?.appContext.config.globalProperties;
/**
 * @property 变量
 */
const latlng = ref<lngLatde>({
    lat: 0,
    lng: 0
})
// 记录员工足迹数量
const footprintNumber = ref<number>(0);
// 选择弹出层
const footprintShow = ref<boolean>(false);
// 弹出成ref
const teamRef = ref();
// 员工Name
const staffName = ref('');
// 时间组件ref
const calendar = ref();
// 年月
const switchTime = ref({
    month: '',
    year: ''
})
// 已有的天数
const arrayDay = ref([]);
// 足迹列表
const footprintList = ref<Array<FootprintItem>>([]);
// 高度
const statusBarHeight = computed(() => { return uni.getSystemInfoSync().statusBarHeight });
// 员工id
const staffId = ref('');
// 地图实例
const mapCxt = ref<any>(null);
// markerlist
const markerList = ref<Array<MarkerItem>>([]);
// 定义图标
const markerIconList = reactive({
    end: '../../static/end.png',
    starting_point: '../../static/starting_point.png',
    def: '../../static/create_drop.jpg'
})
/**
 * @property  所有请求以api开头 如:apiDataInfo
 */
// 员工自己的足迹天数
const apiFootprintDay = async () => {
    const res = await https({
        mode: "footprint",
        name: 'apiGetHasTrackDay',
        data: {
            month: switchTime.value.month,
            year: switchTime.value.year
        }
    })
    arrayDay.value = res?.data?.list || []
}
// 管理者获取员工有足迹的天数
const apiStaffDay = async () => {
    const res = await https({
        mode: "footprint",
        name: 'apiGetStaffHasTrackDay',
        data: {
            month: switchTime.value.month,
            year: switchTime.value.year,
            staff: staffId.value
        }
    })
    arrayDay.value = res?.data?.list || []
}

// 获取用户自己的足迹
const apiGetUserFootprint = (): Promise<Array<LngLat & TypeTime>> => {
    return new Promise(async reslove => {
        const res = await https({
            mode: 'footprint',
            name: 'apiGetTodayTrack',
            data: {}
        })
        if (res.code !== 0) {
            reslove([]);
            return showToast(res.msg);
        }
        if (res.data?.list?.length === 0) {
            showToast('今日还未有足迹可查')
            reslove([]);
        } else {
            reslove(res.data.list)
        }
    })
}
// 管理者查询员工的足迹
const apiGetStaffFootprint = (): Promise<Array<LngLat & TypeTime>> => {
    return new Promise(async reslove => {
        const res = await https({
            mode: 'footprint',
            name: 'apiGetStaffTrack',
            data: {
                staff: teamStore.staffId,
                time: teamStore.recordTime
            }
        })
        if (res.code !== 0) {
            reslove([]);
            return showToast(res.msg);
        }
        if (res.data?.list?.length === 0) {
            showToast('今日还未有足迹可查')
            reslove([]);
        } else {
            reslove(res.data.list)
        }
    })
}
/**
 * @property 自定义事件 以事件名开头 如: clickButton,inputDev
 */
// 年月导出
const yearMonth = () => {
    const time = new Date();

    switchTime.value = {
        year: String(time.getFullYear()),
        month: String(time.getMonth() + 1),
    }
}
// 设置时间
const formatter = () => {
    return arrayDay.value.map(item => ({ date: `${switchTime.value.year}-${switchTime.value.month}-${item}` }))
}
// 进入足迹
const clickFootprint = async () => {
    // 判断是自己查看足迹还是查看员工足迹
    if (userStore.info?.type === 1) {
        await apiFootprintDay();
        teamStore.staffId = 'user';
        let list: Array<LngLat & TypeTime> = await apiGetUserFootprint();
        formatFootprintData(list)
    } else {
        staffId.value && apiStaffDay();
        // 打开弹窗
        footprintShow.value = true;
        teamRef.value.apiManageList()

    }
}

// 确认查看某个员工的足迹
const clickConfirmFootprint = async ({ staff }: { staff: string }) => {

    staffName.value = staff
    const list = await apiGetStaffFootprint();
    formatFootprintData(list)
    calendar.value.close()
}
// 格式话足迹数据
const formatFootprintData = (list: Array<LngLat & TypeTime>) => {
    const data: Array<FootprintItem> = [{
        color: '#275EFF',
        width: 3,
        points: list.map(item => ({
            latitude: Number(item.lat),
            longitude: Number(item.lng),
            ...item
        }))
    }]
    footprintNumber.value = data[0]?.points.length;
    footprintList.value = data;
    latlng.value = {
        lat: Number(list[Math.floor(list.length / 2)]?.lat),
        lng: Number(list[Math.floor(list.length / 2)]?.lng),
    }
    // 创建标记点
    markerList.value = list.map((item, i) => {
        const data = mapStore.formatMarker(item);
        const type = i === 0 ? 'starting_point' : i === list.length - 1 ? 'end' : 'def'
        return {
            ...data,
            iconPath: markerIconList[type],
            callout: {
                ...data.callout as Callout,
                content: item.time.split(' ')[1],
                display: 'ALWAYS'
            },
            mid: i,
            joinCluster: false,
            width: type === 'def' ? 12 : 36,
            height: type === 'def' ? 12 : 36,
            anchor: {
                x: 0.5,
                y: type === 'def' ? 0.5 : 1
            },
            id: i
        }
    })
    mapCxt.value.addMarkers({
        markers: markerList.value,
        clear: true,
    })
}

// 确认日期
const confirmDate = async (e: { fulldate: string }) => {
    teamStore.recordTime = e.fulldate;
}
// 退出足迹
const clickExitFootprints = () => {
    teamStore.staffId = '';
    teamStore.recordTime = '';
    uni.navigateBack();
}
// 切换月份
const switchMonth = (e: StaffHas) => {
    switchTime.value = {
        month: String(e.month),
        year: String(e.year)
    };
    clickFootprint();

}
// 打开弹窗
const openTimeShow = () => {
    calendar.value.open();
}
// 选择完打开弹窗
const confirmStaff = (staff: string) => {
    if (!staff) return showToast('请先选择员工')
    staffId.value = staff
    openTimeShow();
}
// 选择的员工发生变化
const staffChange = (staff: string) => {
    staffId.value = staff;
    apiStaffDay();
}
// 显示 时间
const clickShowTitle = () => {
    markerList.value = markerList.value.map((item, i) => {
        return {
            ...item,
            callout: {
                ...item.callout as Callout,
                display: item.callout?.display === 'ALWAYS' ? 'BYCLICK' : 'ALWAYS'
            },
        }
    })
    mapCxt.value.addMarkers({
        markers: markerList.value,
        clear: true,
    })
}
/** 
 * @property 内置方法
 */
onLoad(async () => {
    latlng.value = await currentLocation() as { lng: string; lat: string };
})
onReady(() => {
    yearMonth();
    clickFootprint();
    mapCxt.value = uni.createMapContext('map', _that);
})
</script>
<template>
    <div class="w-[100vw] h-[100vh]">
        <map name="mapID" class="w-[100vw] h-[100vh]" id="map" :longitude="latlng.lng" :latitude="latlng.lat"
            :polyline="footprintList"></map>
    </div>
    <!-- 弹出层 -->
    <SelecTeam :is-show="footprintShow" @close="footprintShow = false" ref="teamRef" type="footprint"
        title="请选择要查看足迹的员工" @confirm="clickConfirmFootprint" @staffChange="staffChange">
        <template #other="row">
            <div class="font-size-28 p-3.5" @click="confirmStaff(row.seaff)">{{ teamStore.recordTime || '请选择日期' }}</div>
        </template>
    </SelecTeam>
    <!-- 日期选择器 -->
    <uni-calendar :clearDate="false" :insert="false" @change="confirmDate" @confirm="confirmDate" startDate="2024-10-21"
        :endDate="timeFormat(null)" ref="calendar" :selected="formatter()" @monthSwitch="switchMonth" />
    <!-- 员工足迹 -->
    <div class="fixed top-0 w-[100vw] bg-[#fff] z-1000">
        <div :style="{
            height: statusBarHeight + 'px'
        }">
        </div>
        <div class="h-[44px] fra font-size-24">
            <text v-if="teamStore.staffId !== 'user'">员工：{{ staffName }}的足迹({{ footprintNumber }})条记录</text>
            <text v-else class="pl-3.5">({{ footprintNumber }})条记录</text>
            <text class="ml-3 c-red" @click="clickExitFootprints">退出足迹</text>
            <text class="ml-3 c-[#2787F5]" @click="footprintShow = true" v-if="!authStaff()">切换</text>
        </div>
    </div>
    <div class="p-2 b-rd-1 bg-[#fff] fc font-size-24 fixed left-20 bottom-[120px] w-50 h-50 b-rd-1"
        @click="clickShowTitle">
        Aa
    </div>
</template>
<style lang="scss" scoped>
:deep(.uni-calendar__content) {
    z-index: 109876 !important;
}
</style>